import { eventType } from './utils'

class PlotManager extends cc.Node {
    constructor() {
        super()

        this.plotConfig = null
        this.prefabMap = {}

        this.on(eventType.showPlotById, this.showPlotById, this)
        this.on(eventType.showMessage, this.showMessage, this)
        this.loadPlotConfig()
    }

    loadPlotConfig() {
        cc.loader.loadRes('config/plotConfig', cc.JsonAsset, (err, res) => {
            if (err) {
                // throw new Error('剧情加载失败', err)
                console.log('剧情加载失败', err)
            }
            // console.log(res.json)
            this.plotConfig = res.json
        })
    }

    showPlotById(id) {
        this.pop('ui/plotWindow')
            .then(node => {
                const config = this.getConfigById(id)
                node.getComponent('plotWindow').init(config)
            })
    }

    getConfigById(id) {
        const config = this.plotConfig.plot[id]
        const personList = this.plotConfig.person

        if (!config) {
            throw new Error('剧情不存在')
        }

        config.dialogs.forEach(el => {
            el.person = personList.find(p => p.id == el.personId)
        })

        return config
    }

    showMessage(message) {

    }

    pop(prefabPath, parentNode) {
        parentNode = parentNode || cc.director.getScene().getChildByName("Canvas")
        return new Promise((resolve, reject) => {
            cc.loader.loadRes(prefabPath, (err, prefabRes) => {
                if (err) {
                    cc.warn("async load prefab failed : ", prefabPath)
                    reject()
                }
                let popNode = cc.instantiate(prefabRes)
                parentNode.addChild(popNode, 99)
                resolve(popNode)
            })
        })
    }
}

export default new PlotManager()